package com.kingdee.webapi.javasdk.purpurchaseorder;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.kingdee.webapi.javasdk.common.HttpRequestUtil;
import com.kingdee.webapi.javasdk.common.SeqHelper;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.fail;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PurPurchaseOrderJdy2Cy {
//    static final Log log = LogFactory.getLog(PurPurchaseOrderJdy2Cy.class);
    static final Logger log = LogManager.getLogger(PurPurchaseOrderJdy2Cy.class);
    K3CloudApi api = new K3CloudApi();
    static String engineCode = "iskos7m6c2f9gp0wqcn7ielly";
    static String engineSecret = "BFqZ8M35luiHgg3vwd46rytkkQP38s2LJWro0EG3oLfyiKKIUi6Xly==";
    static String contentType = "application/json";
    String urlCy = "https://www.h3yun.com/OpenApi/Invoke";
    static String FNumber = SeqHelper.genNumber("CGDD");
    static String FName = "aucgdd_" + UUID.randomUUID().toString();

    //氚云辅料采购单单据编码
    static String schemaCodeCYFLCG = "D279357Sh1hjskmjufjwh8e3volp6ruly";
    static String schemaCodeCYFLCG2 = "D279357Sc8hmh59cf10unmlmtaytvb7ly";

    static String schemaCodeSCJHDD = "xgawkup5u6xm5xr0f4ylz37ly";

    static Cache<String, String> cache = Caffeine.newBuilder().maximumSize(10000).expireAfterWrite(48, TimeUnit.HOURS).build();



    String json = "{\n" +
            "  \"NeedUpDateFields\": [],\n" +
            "  \"NeedReturnFields\": [],\n" +
            "  \"IsDeleteEntry\": \"true\",\n" +
            "  \"SubSystemId\": \"\",\n" +
            "  \"IsVerifyBaseDataField\": \"false\",\n" +
            "  \"IsEntryBatchFill\": \"true\",\n" +
            "  \"ValidateFlag\": \"true\",\n" +
            "  \"NumberSearch\": \"true\",\n" +
            "  \"IsAutoAdjustField\": \"false\",\n" +
            "  \"InterationFlags\": \"\",\n" +
            "  \"IgnoreInterationFlag\": \"\",\n" +
            "  \"Model\": {\n" +
            "    \"FBillTypeID\": {\n" +
            "      \"FNUMBER\": \"CGDD01_SYS\"\n" +
            "    },\n" +
            "    \"FDate\": \"2022-04-25 00:00:00\",\n" +
            "    \"FSupplierId\": {\n" +
            "      \"FNumber\": \"SCMGYS000002\"\n" +
            "    },\n" +
            "    \"FPurchaseOrgId\": {\n" +
            "      \"FNumber\": \"100\"\n" +
            "    },\n" +
            "    \"FPurchaseDeptId\": {\n" +
            "      \"FNumber\": \"FINBM000200\"\n" +
            "    },\n" +
            "    \"FPurchaserGroupId\": {\n" +
            "      \"FNumber\": \"FINYWZ000203\"\n" +
            "    },\n" +
            "    \"FPurchaserId\": {\n" +
            "      \"FNumber\": \"FINYG000202\"\n" +
            "    },\n" +
            "    \"FProviderId\": {\n" +
            "      \"FNumber\": \"SCMGYS000002\"\n" +
            "    },\n" +
            "    \"FSettleId\": {\n" +
            "      \"FNumber\": \"SCMGYS000002\"\n" +
            "    },\n" +
            "    \"FChargeId\": {\n" +
            "      \"FNumber\": \"SCMGYS000002\"\n" +
            "    },\n" +
            "    \"FChangeStatus\": \"A\",\n" +
            "    \"FACCTYPE\": \"Q\",\n" +
            "    \"FPOOrderFinance\": {\n" +
            "      \"FSettleModeId\": {\n" +
            "        \"FNumber\": \"JSFS01_SYS\"\n" +
            "      },\n" +
            "      \"FPayConditionId\": {\n" +
            "        \"FNumber\": \"FKTJ01_SYS\"\n" +
            "      },\n" +
            "      \"FSettleCurrId\": {\n" +
            "        \"FNumber\": \"PRE001\"\n" +
            "      },\n" +
            "      \"FExchangeTypeId\": {\n" +
            "        \"FNumber\": \"HLTX01_SYS\"\n" +
            "      },\n" +
            "      \"FExchangeRate\": 1,\n" +
            "      \"FPriceTimePoint\": \"1\",\n" +
            "      \"FFOCUSSETTLEORGID\": {\n" +
            "        \"FNumber\": \"100\"\n" +
            "      },\n" +
            "      \"FIsIncludedTax\": true,\n" +
            "      \"FISPRICEEXCLUDETAX\": true,\n" +
            "      \"FLocalCurrId\": {\n" +
            "        \"FNumber\": \"PRE001\"\n" +
            "      },\n" +
            "      \"FSupToOderExchangeBusRate\": 1\n" +
            "    },\n" +
            "    \"FPOOrderEntry\": [\n" +
            "      {\n" +
            "        \"FProductType\": \"1\",\n" +
            "        \"FMaterialId\": {\n" +
            "          \"FNumber\": \"SCMWL000012\"\n" +
            "        },\n" +
            "        \"FMaterialDesc\": \"SCMWL000012采购(可退物料)\",\n" +
            "        \"FUnitId\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FQty\": 6,\n" +
            "        \"FPriceUnitId\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FPriceUnitQty\": 6,\n" +
            "        \"FPriceBaseQty\": 6,\n" +
            "        \"FDeliveryDate\": \"2022-04-25 15:03:00\",\n" +
            "        \"FPrice\": 796.460177,\n" +
            "        \"FTaxPrice\": 900,\n" +
            "        \"FEntryTaxRate\": 13,\n" +
            "        \"FRequireOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FRequireDeptId\": {\n" +
            "          \"FNumber\": \"SCMBM000001\"\n" +
            "        },\n" +
            "        \"FReceiveOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FEntrySettleOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FStockUnitID\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FStockQty\": 6,\n" +
            "        \"FStockBaseQty\": 6,\n" +
            "        \"FSupplierLot\": \"11111111111\",\n" +
            "        \"FDeliveryMaxQty\": 6,\n" +
            "        \"FDeliveryMinQty\": 6,\n" +
            "        \"FDeliveryEarlyDate\": \"2022-04-25 15:03:00\",\n" +
            "        \"FDeliveryLastDate\": \"2022-04-25 15:03:00\",\n" +
            "        \"FPriceCoefficient\": 1,\n" +
            "        \"FEntrySettleModeId\": {\n" +
            "          \"FNumber\": \"JSFS01_SYS\"\n" +
            "        },\n" +
            "        \"FReqTraceNo\": \"1111111111\",\n" +
            "        \"FPlanConfirm\": true,\n" +
            "        \"FSalUnitID\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FSalQty\": 6,\n" +
            "        \"FCentSettleOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FDispSettleOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FDeliveryStockStatus\": {\n" +
            "          \"FNumber\": \"KCZT02_SYS\"\n" +
            "        },\n" +
            "        \"FSalBaseQty\": 6,\n" +
            "        \"FEntryPayOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FAllAmountExceptDisCount\": 5400,\n" +
            "        \"FEntryDeliveryPlan\": [\n" +
            "          {\n" +
            "            \"FDeliveryDate_Plan\": \"2022-04-25 15:03:00\",\n" +
            "            \"FPlanQty\": 6,\n" +
            "            \"FPREARRIVALDATE\": \"2022-04-25 15:03:00\"\n" +
            "          }\n" +
            "        ]\n" +
            "      },\n" +
            "      {\n" +
            "        \"FProductType\": \"1\",\n" +
            "        \"FMaterialId\": {\n" +
            "          \"FNumber\": \"SCMWL000012\"\n" +
            "        },\n" +
            "        \"FMaterialDesc\": \"SCMWL000012采购(可退物料)\",\n" +
            "        \"FUnitId\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FQty\": 6,\n" +
            "        \"FPriceUnitId\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FPriceUnitQty\": 6,\n" +
            "        \"FPriceBaseQty\": 6,\n" +
            "        \"FDeliveryDate\": \"2022-04-25 15:03:18\",\n" +
            "        \"FPrice\": 796.460177,\n" +
            "        \"FTaxPrice\": 900,\n" +
            "        \"FEntryTaxRate\": 13,\n" +
            "        \"FRequireOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FReceiveOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FEntrySettleOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FStockUnitID\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FStockQty\": 6,\n" +
            "        \"FStockBaseQty\": 6,\n" +
            "        \"FDeliveryMaxQty\": 6,\n" +
            "        \"FDeliveryMinQty\": 6,\n" +
            "        \"FDeliveryEarlyDate\": \"2022-04-25 15:03:18\",\n" +
            "        \"FDeliveryLastDate\": \"2022-04-25 15:03:18\",\n" +
            "        \"FPriceCoefficient\": 1,\n" +
            "        \"FEntrySettleModeId\": {\n" +
            "          \"FNumber\": \"JSFS01_SYS\"\n" +
            "        },\n" +
            "        \"FPlanConfirm\": true,\n" +
            "        \"FSalUnitID\": {\n" +
            "          \"FNumber\": \"Pcs\"\n" +
            "        },\n" +
            "        \"FSalQty\": 6,\n" +
            "        \"FCentSettleOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FDispSettleOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FDeliveryStockStatus\": {\n" +
            "          \"FNumber\": \"KCZT02_SYS\"\n" +
            "        },\n" +
            "        \"FSalBaseQty\": 6,\n" +
            "        \"FEntryPayOrgId\": {\n" +
            "          \"FNumber\": \"100\"\n" +
            "        },\n" +
            "        \"FAllAmountExceptDisCount\": 5400,\n" +
            "        \"FEntryDeliveryPlan\": [\n" +
            "          {\n" +
            "            \"FDeliveryDate_Plan\": \"2022-04-25 15:03:18\",\n" +
            "            \"FPlanQty\": 6,\n" +
            "            \"FSUPPLIERDELIVERYDATE\": \"2022-04-25 15:03:18\",\n" +
            "            \"FPREARRIVALDATE\": \"2022-04-25 15:03:18\"\n" +
            "          }\n" +
            "        ]\n" +
            "      }\n" +
            "    ],\n" +
            "    \"FIinstallment\": [\n" +
            "      {\n" +
            "        \"FYFRATIO\": 100,\n" +
            "        \"FYFAMOUNT\": 10800\n" +
            "      }\n" +
            "    ],\n" +
            "    \"FBillNo\": "+"\""+FNumber+"\""+",\n" +
            "  },\n" +
            "  \"TargetFormId\": \"0\"\n" +
            "}";


    /* 本接口用于实现采购订单 (PUR_PurchaseOrder)的保存功能 */
    @Test
    public void atestSavePurchaseOrder() throws Exception {
        String result = api.save("PUR_PurchaseOrder", json);
        Gson gson = new Gson();
        RepoRet sRet = gson.fromJson(result, RepoRet.class);
        if (sRet.isSuccessfully()) {

            System.out.printf("%s%n", gson.toJson(sRet.getResult()));
        } else {
            fail("采购订单保存接口: " + gson.toJson(sRet.getResult()));
        }
    }


    /*本接口用于实现采购订单 (PUR_PurchaseOrder)的提交功能*/
    @Test
    public void btestSubmitPurchaseOrder() throws Exception {
        JsonObject jsonData = new JsonObject();
        jsonData.addProperty("Numbers", FNumber);
        String result = api.submit("PUR_PurchaseOrder", jsonData.toString());
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("采购订单提交接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("采购订单提交接口: " + gson.toJson(repoRet.getResult()));
        }

    }

    /*本接口用于实现采购订单 (PUR_PurchaseOrder)的审核功能*/
    @Test
    public void ctestauditPurchaseOrder() throws Exception {
        JsonObject jsonData = new JsonObject();
        jsonData.addProperty("Numbers", FNumber);
        String result = api.audit("PUR_PurchaseOrder", jsonData.toString());
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("采购订单审核接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("采购订单审核接口: " + gson.toJson(repoRet.getResult()));
        }

    }

    /*本接口用于实现采购订单 (PUR_PurchaseOrder)的反审核功能*/
    @Test
    public void dtestunauditPurchaseOrder() throws Exception {
        JsonObject jsonData = new JsonObject();
        jsonData.addProperty("Numbers", FNumber);
        String result = api.unAudit("PUR_PurchaseOrder", jsonData.toString());
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("采购订单反审核接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("采购订单反审核接口: " + gson.toJson(repoRet.getResult().getResponseStatus()));
        }
    }



    /*本接口用于实现采购订单 (PUR_PurchaseOrder)的查看功能*/
    @Test
    public void gtestviewPurchaseOrder() throws Exception {
        JsonObject jsonData = new JsonObject();
        jsonData.addProperty("Number", FNumber);
        String result = api.view("PUR_PurchaseOrder", jsonData.toString());
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("采购订单查看接口: %s%n", result);
        } else {
            fail("采购订单查看接口: " + result);
        }
    }



    /**
     * 预处理采购订单，用于获取待同步订单清单
     * 查询金蝶修改日期为当日且审核通过的订单清单，然后在氚云检测是否已有，返回氚云没有的订单清单
     */
    @Test
    public void preprocessCGDDList() throws Exception {
        //0-6 供应商, 采购日期, 单据编号, 客户合同号, 朔翔号（订单号）, 单据提内码
        // 最后： FModifyDate
        // [[101527, 2023-07-06T00:00:00, 0, CGDD007360, null, 1TSGW8, null, 270048.0, 张 结算, 2023-07-10T00:00:00, 289139, 2023-07-05T17:54:50.953, 107592, B]]
        String fieldstr = "FSupplierId.Fname,FDate,FBillNo, FMtoNo, F_qwe_Text4, FPOOrderEntry_FEntryID, " +
                "FModifyDate";
        String modifyDate = "2023-7-7";
        String json = "{\n" +
                "    \"FormId\": \"PUR_PurchaseOrder\",\n" +
                "    \"FieldKeys\": \"" + fieldstr + "\",\n" +
                "    \"FilterString\": \"FModifyDate>=\'" + modifyDate + "\' and FDocumentStatus=\'C\'\",\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 2000,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        try {
            String result = String.valueOf(api.executeBillQuery(json));
            if (result.length() > 2) {
                String[][] formatResult = formatJdyData(result);
                for (int i=0; i<formatResult.length; i++) {
                    String billNoEntryId = formatResult[i][2] + "-" + formatResult[i][5];
                    if (cache.getIfPresent(billNoEntryId) != null) {
                        continue;
                    } else {
                        // 查询氚云，如存在则写入cache后，continue
                        String strFilter = "{\"FromRowNum\":   0,\"RequireCount\": false,\"ReturnItems\": [],   " +
                                "\"SortByCollection\": [],\"ToRowNum\": 500,   \"Matcher\":{\"Type\":\"And\",   \"Matchers\":[{\"Type\":\"And\"," +
                                "\"Matchers\":[{\"Type\":\"Item\",\"Name\":\"F0000013\",\"Operator\":2,\"Value\":\"CGDD000056\"}]}]}}";
//                        String strFilter = "{\"FromRowNum\":0,\"RequireCount\":false,\"ReturnItems\":["ObjectId", "F0000039", "F0000013"],\"SortByCollection\":[],\"ToRowNum\":500,\"Matcher\":{\"Type\":\"And\",\"Matchers\":[{\"Type\":\"Item\",\"Name\":\"F0000039\",\"Operator\":2,\"Value\":\"CGDD007035-119130\"}]}}";
                        String reData = queryCYDatas(schemaCodeCYFLCG, strFilter);
                        if (reData.contains("{\"Successful\":true,")) {
                            if (reData.length() > 110) {
                                System.out.println("该单号已存在: ");
                                cache.put(billNoEntryId, "存在");
                            } else {
                                // 尚不存在，同步到氚云

                            }
                        }
                        // 如不存在则写入氚云
                    }
                }
                System.out.println("formatResult: " + formatResult);
            }
            System.out.println("采购订单单据查询接口: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 金蝶采购订单 To 氚云辅料采购单
     * 用于历史数据批量迁移
     * @throws Exception
     */
    @Test
    public void syncJdyData2Cy()  throws Exception{
        String gdStr = "CGDD";
        String bdStr = "";
        for (int i = 7665; i<=7665; i++) {
            System.out.println("i = " + i);
            bdStr = gdStr + String.format("%06d", i);
            htestQueryPurchaseOrder(bdStr);
        }
    }

    /*本接口用于实现采购订单 (PUR_PurchaseOrder)的单据查询功能*/
//    @Test
    public void htestQueryPurchaseOrder(String FNumber) throws Exception {
//        FNumber = "CGDD007665";
        //0-5 供应商, 采购日期, 采购员, 单据编号, 采购订单号
        //5-5 客户合同号, 物料名称, 采购数量, 规格型号, 交货日期
        //10-4 补充说明备注, 创建人, 创建日期, 产品名称
        //14-6 实体主键, 单据状态, 朔翔号（订单号）, 备注1（辅料规格; 先占位）, 对应产品（产品名称）, 跟单员名称（业务员）
        //20 纸箱纸质要求（F_QWE_TEXT）, 使用说明（F_QWE_TEXT2）, 备注（FEntryNote）, 审核日期 ,
        // 最后： FModifyDate  ($$FAUXPROPID__FF100002,)
        // [[101527, 2023-07-06T00:00:00, 0, CGDD007360, null, 1TSGW8, null, 270048.0, 张 结算, 2023-07-10T00:00:00, 289139, 2023-07-05T17:54:50.953, 107592, B]]
        String fieldstr = "FSupplierId.Fname,FDate,FPurchaserId.Fname,FBillNo,FPURCHASEORDERNO, " +
                "FMtoNo,FMaterialName,FQty,FModel,FDeliveryDate," +
                "F_qwe_Text1, FCreatorId.fname,FCreateDate, F_qwe_Base, " +
                "FID,FDocumentStatus, F_qwe_Text4, FAUXPROPID.FF100002, F_QWE_BASE1.fname, F_qwe_Text6," +
                "F_QWE_TEXT, F_QWE_TEXT2, FEntryNote,  FApproveDate, " +
                "FModifyDate";
        String json = "{\n" +
                "    \"FormId\": \"PUR_PurchaseOrder\",\n" +
                "    \"FieldKeys\": \"" + fieldstr + "\",\n" +
                "    \"FilterString\": \"FBillNo=\'" + FNumber + "\' and FDocumentStatus=\'C\'\",\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 2000,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        String result = String.valueOf(api.executeBillQuery(json));
        if (result.length() > 2) {
            String[][] formatResult = formatJdyData(result);
            for (int i=0; i<formatResult.length; i++) {
                createCYData(schemaCodeCYFLCG, formatCyData(formatResult[i]));
            }
            System.out.println("formatResult: " + formatResult);
        }
        System.out.println("采购订单单据查询接口: " + result);
    }

    public String formatCyData(String[] jdyStr) {
        //0-5 供应商, 采购日期, 采购员, 单据编号, 采购订单号
        //5-5 客户合同号, 物料名称, 采购数量, 规格型号, 交货日期
        //10-4 补充说明备注, 创建人, 创建日期, 产品名称
        //14-6 实体主键, 单据状态, 朔翔号（订单号）, 备注1（辅料规格; 先占位）, 对应产品（产品名称）, 跟单员名称（业务员）
        //20 纸箱纸质要求（F_QWE_TEXT）, 使用说明（F_QWE_TEXT2）, 备注（FEntryNote）,
        // 最后： FModifyDate

        String cyData = "{\"F0000029\":\"供应商\",\"F0000031\":\"采购日期\",\"F0000035\":\"业务员（文本）\",\"F0000013\":\"采购订单号\"," +
                "\"F0000026\":\"客户合同号\",\"F0000017\":\"产品名称\",\"F0000021\":\"物料名称\",\"F0000024\":采购数量,\"F0000022\":\"辅料规格\",\"F0000028\":\"交货日期\"," +
                "\"F0000030\":\"补充备注说明\",\"F0000033\":\"创建人（文本）\",\"CreatedBy\":\"858c3e2a-b79f-410e-96eb-8e74c3b526d8\",\"CreatedTime\":\"2023/7/7 16:16:16\",\"OwnerId\":\"858c3e2a-b79f-410e-96eb-8e74c3b526d8\"," +
                "\"F0000034\":\"订单号\",\"F0000036\":\"纸箱纸质要求\", \"F0000037\":\"使用说明\", \"F0000038\":\"99备注99\"}";
        cyData = cyData.replaceAll("供应商", jdyStr[0]);
        cyData = cyData.replaceAll("采购日期", jdyStr[1]);
        cyData = cyData.replaceAll("业务员（文本）", jdyStr[19]);
        cyData = cyData.replaceAll("采购订单号", jdyStr[3]);

        cyData = cyData.replaceAll("客户合同号", jdyStr[5]);
        cyData = cyData.replaceAll("物料名称", jdyStr[6]);
        cyData = cyData.replaceAll("采购数量", jdyStr[7]);
        cyData = cyData.replaceAll("辅料规格", jdyStr[17]);
        cyData = cyData.replaceAll("交货日期", jdyStr[9]);

        cyData = cyData.replaceAll("补充备注说明", jdyStr[10]);
        cyData = cyData.replaceAll("创建人（文本）", jdyStr[11]);
        cyData = cyData.replaceAll("产品名称", jdyStr[18]);
        cyData = cyData.replaceAll("订单号", jdyStr[16]);
        cyData = cyData.replaceAll("纸箱纸质要求", jdyStr[20]);

        cyData = cyData.replaceAll("使用说明", jdyStr[21]);
        cyData = cyData.replaceAll("99备注99", jdyStr[22]);
        System.out.println("cyData: " + cyData);
        return cyData;

    }

    public String[][] formatJdyData(String str) {
        // 去掉字符串中的空格
        str = str.replaceAll("\\s+","");

        // 去掉每个元素的方括号，并将逗号分隔的元素转换为数组
        String[] arr = str.substring(2, str.length() - 2).split("\\],\\[");

        // 将每个一维数组元素转换为Java数组
        String[][] result = new String[arr.length][];
        for (int i = 0; i < arr.length; i++) {
            String[] temp = arr[i].split(",");
//            for (int j = 0; j < temp.length; j++) {
//                temp[j] = temp[j].replaceAll("\"", "");
//            }
            result[i] = temp;
        }

        // 使用循环遍历访问每个元素
//        for (int i = 0; i < result.length; i++) {
//            for (int j = 0; j < result[i].length; j++) {
//                System.out.print(result[i][j] + " ");
//            }
//            System.out.println();
//        }
        return result;
    }

    public void createCYData(String schemaCode, String jsonData) {
        // 1. 组装数据验证
        // 2. 考虑重试场景数据判重问题
        // 3. 重试机制思考
        // 4.
        if (jsonData == null || schemaCode == null) {
            return;
        }
        // 验证可行的测试数据，用于辅料采购单创建测试
//        jsonData = "{\"F0000029\":\"供应商-测试\",\"F0000031\":\"2023/7/7 0:00:00\",\"F0000032\":\"7f0ec4f5-9ce6-4abb-9a95-35eb1635d08c\",\"F0000013\":\"订单号-测试\",\"F0000026\":\"合同号-测试\",\"F0000017\":\"产品名称-测试\",\"F0000021\":\"物料名称-测试\",\"F0000024\":66,\"F0000022\":\"辅料规格-测试\",\"F0000028\":\"2023/7/11 0:00:00\",\"F0000030\":\"补充备注说明-测试\",\"F0000025\":[\"e5c4f77d-7d37-4154-9403-0b8d4b5858d9\",\"f4efea6c-4cfa-4c05-a3ab-76c75cf0e718\"],\"CreatedBy\":\"858c3e2a-b79f-410e-96eb-8e74c3b526d8\",\"CreatedTime\":\"2023/7/7 16:16:16\",\"OwnerId\":\"858c3e2a-b79f-410e-96eb-8e74c3b526d8\"}";

        Map<String, String> paramMap = new HashMap();
        paramMap.put("ActionName", "CreateBizObject");
        paramMap.put("SchemaCode", schemaCode);
        paramMap.put("BizObject", jsonData);
        paramMap.put("IsSubmit", "true");
        //身份认证参数
        Map headers = new HashMap();
        headers.put("EngineCode", engineCode);
        headers.put("EngineSecret", engineSecret);
        headers.put("Content-Type", contentType);
        Gson gson = new Gson();
        String result = HttpRequestUtil.sendPost(urlCy,   gson.toJson(paramMap), headers);
        log.info("【" + schemaCode + "】的氚云单据创建完成，返回结果为：" + result + "   入参为：" + jsonData);
    }

    public void createCYData(String schemaCode, String jsonData, String isSubmit) {
        // 1. 组装数据验证
        // 2. 考虑重试场景数据判重问题
        // 3. 重试机制思考
        // 4.
        if (jsonData == null || schemaCode == null) {
            return;
        }
        // 验证可行的测试数据，用于辅料采购单创建测试
//        jsonData = "{\"F0000029\":\"供应商-测试\",\"F0000031\":\"2023/7/7 0:00:00\",\"F0000032\":\"7f0ec4f5-9ce6-4abb-9a95-35eb1635d08c\",\"F0000013\":\"订单号-测试\",\"F0000026\":\"合同号-测试\",\"F0000017\":\"产品名称-测试\",\"F0000021\":\"物料名称-测试\",\"F0000024\":66,\"F0000022\":\"辅料规格-测试\",\"F0000028\":\"2023/7/11 0:00:00\",\"F0000030\":\"补充备注说明-测试\",\"F0000025\":[\"e5c4f77d-7d37-4154-9403-0b8d4b5858d9\",\"f4efea6c-4cfa-4c05-a3ab-76c75cf0e718\"],\"CreatedBy\":\"858c3e2a-b79f-410e-96eb-8e74c3b526d8\",\"CreatedTime\":\"2023/7/7 16:16:16\",\"OwnerId\":\"858c3e2a-b79f-410e-96eb-8e74c3b526d8\"}";

        Map<String, String> paramMap = new HashMap();
        paramMap.put("ActionName", "CreateBizObject");
        paramMap.put("SchemaCode", schemaCode);
        paramMap.put("BizObject", jsonData);
        paramMap.put("IsSubmit", isSubmit);
//        paramMap.put("Status", "0");
        //身份认证参数
        Map headers = new HashMap();
        headers.put("EngineCode", engineCode);
        headers.put("EngineSecret", engineSecret);
        headers.put("Content-Type", contentType);
        Gson gson = new Gson();
        String result = HttpRequestUtil.sendPost(urlCy,   gson.toJson(paramMap), headers);
        log.info("【" + schemaCode + "】的氚云单据创建完成，返回结果为：" + result + "   入参为：" + jsonData);
    }

    @Test
    public void queryCYData() {
        Map<String, String> paramMap = new HashMap();
        paramMap.put("ActionName", "LoadBizObject");
        paramMap.put("SchemaCode", "xgawkup5u6xm5xr0f4ylz37q0");
        paramMap.put("BizObjectId","85758cb9-f84a-415b-9263-ec86ef1f8df1");
//身份认证参数.
        Map headers = new HashMap();
        headers.put("EngineCode", engineCode);
        headers.put("EngineSecret", engineSecret);
        headers.put("Content-Type",contentType);

        Gson gson = new Gson();
        String result = HttpRequestUtil.sendPost(urlCy,   gson.toJson(paramMap), headers);

        System.out.println("result: " + result);
    }

    public String queryCYDatas(String schemaCode, String filter) {
        Map<String, String> paramMap = new HashMap();
        paramMap.put("ActionName", "LoadBizObjects");
        paramMap.put("SchemaCode", schemaCode);
        paramMap.put("Filter", filter);
        //身份认证参数.
        Map headers = new HashMap();
        headers.put("EngineCode", engineCode);
        headers.put("EngineSecret", engineSecret);
        headers.put("Content-Type", contentType);

        Gson gson = new Gson();
        String result = HttpRequestUtil.sendPost(urlCy, gson.toJson(paramMap), headers);
        return result;
    }

    /*本接口用于实现采购订单 (PUR_PurchaseOrder)的删除功能*/
    @Test
    public void itestdeletePurchaseOrder() throws Exception {
        JsonObject jsonData = new JsonObject();
        jsonData.addProperty("Numbers", FNumber);
        String result = api.delete("PUR_PurchaseOrder", jsonData.toString());
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("采购订单删除接口: %s%n", gson.toJson(repoRet.getResult().getResponseStatus()));
        } else {
            fail("采购订单删除接口: " + gson.toJson(repoRet.getResult().getResponseStatus()));
        }
    }


    /*本接夺口用于实现生产计划订单 (k1583e5bde51d45a299c0126e98951888)的单据查询功能*/
    @Test
    public void queryJdyScjhdd() throws Exception {
        String FNumber = "20211101-0005";
        //0-5 单据编号, 朔翔号, 产品名称（子）, 合并客户合同号, 级别,
        //5-5 二次加工, 验货日, 交货日期, 货号, 合并装箱率,
        //10-5 总箱数, 产品数量合计, 备注, 配件名称, 颜色,
        //15-5 材质, 重量g, 需求数量（个), 备注（子表）, 模具编号,
        //20-5 出模率,审核日期, 单据状态, 子表1ID, 子表2ID,
        //25  订单用料
        //25 ,
        // 最后： 行号, FModifyDate  ($$FAUXPROPID__FF100002,)
        // [[101527, 2023-07-06T00:00:00, 0, CGDD007360, null, 1TSGW8, null, 270048.0, 张 结算, 2023-07-10T00:00:00, 289139, 2023-07-05T17:54:50.953, 107592, B]]
        String fieldstr = "FBillNo, F_qwe_Text6, F_qwe_Base3.Fname, F_qwe_Text5, F_qwe_Text7, " +
                " F_qwe_Text2, F_qwe_Date1, F_qwe_Date, F_qwe_Text19, F_qwe_Text13, " +
                " F_qwe_Decimal5, F_qwe_Decimal1, F_qwe_Text21, F_qwe_Base.Fname, F_qwe_Text16, " +
                " F_qwe_Text17, F_qwe_BaseProperty1, F_qwe_Decimal, F_qwe_Text3, F_qwe_BaseProperty3, " +
                " F_qwe_BaseProperty4, F_QWE_DATE19, FBillStatus1, F_qwe_Entity1_FEntryID, F_qwe_Entity_FEntryID, " +
                " F_ddyl, " +
                " 'test-ly', " +
                " F_qwe_Text12 ";
        String json = "{\n" +
                "    \"FormId\": \"k1583e5bde51d45a299c0126e98951888\",\n" +
                "    \"FieldKeys\": \"" + fieldstr + "\",\n" +
                "    \"FilterString\": \"FBillNo=\'" + FNumber + "\' and FBillStatus1=\'1\'\",\n" +
//                "    \"FilterString\": \"FBillNo=\'" + FNumber + "\'\",\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 0,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        String result = String.valueOf(api.executeBillQuery(json));
//        if (result.length() > 2) {
//            String[][] formatResult = formatJdyData(result);
//            for (int i=0; i<formatResult.length; i++) {
//                createCYData(formatCyData(formatResult[i]));
//            }
//            System.out.println("formatResult: " + formatResult);
//        }
        System.out.println("生产订单单据查询接口: " + result);
    }









   public static void main(String[] args) {
        PurPurchaseOrderJdy2Cy p = new PurPurchaseOrderJdy2Cy();
        log.info("同步程序已启动！");
        TimerTask task = new TimerTask() {
            public void run() {
                try {
                    // 在此处编写需要定时执行的代码
                    String endDate = LocalDate.now().plusDays(1).toString();
                    String beginDate = LocalDate.now().minusDays(1).toString();
                    log.info("定时器执行,同步区间：（" + beginDate + " -- " + endDate + ")");
                    p.processCGDDJdy2Cy(beginDate, endDate);
                    p.processSCJHDDJdy2Cy(beginDate, endDate);
                } catch (Exception e) {
                    log.error("定时器执行异常。", e);
                }
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, 0, 60000); // 第二个参数为延迟时间，第三个参数为间隔时间


//       try { 在此处编写需要定时执行的代码
//           String endDate = LocalDate.now().plusDays(1).toString();
//           String beginDate = LocalDate.now().minusDays(1).toString();
//           log.info("定时器执行,同步区间：（" + beginDate + " -- " + endDate + ")");
////                    p.processCGDDJdy2Cy(beginDate, endDate);
//           p.processSCJHDDJdy2Cy(beginDate, endDate);
//       } catch (Exception e) {
//           log.error("定时器执行异常。", e);
//       }
           //




//       // 获取当前日期头一日（从头一天开始,从修改日期在时间范围内，且金蝶获取审核通过的清单，按订单编号排序）
//       LocalDate endDate = LocalDate.now().plusDays(1);
//       LocalDate beginDate = LocalDate.now().minusDays(10);
//       while(!(endDate.getYear() == 2021 && endDate.getMonthValue() == 9)) {
//
//           try{
//               p.processCGDDJdy2Cy(beginDate.toString(), endDate.toString());
//               log.info("当前处理日期： " + beginDate.toString());
//
//               endDate = endDate.minusDays(10);
//               beginDate = beginDate.minusDays(10);
//           } catch (Exception e) {
//               log.error(e.toString());
//           }
//       }
    }


//    @Test
    public void processCGDDJdy2Cy(String beginDate, String endDate) throws Exception {
        // 查询Jdy数据，入参：头一天日期；出参：二维数组，空返回null
        String[][] JdyCGDD = queryPurchaseOrderBySort(beginDate, endDate);
        if (JdyCGDD == null || JdyCGDD.length==0) {
            return;
        }
        // 氚云辅料采购订单vo
        CyCGDDVO cyCgddVo = null;
        // 对Jdy循环处理。
        // 0.判断该单据在cy是否存在，存在则对所有该单据continue（利用java自带缓存）
        // 1.按顺序判断是否新单据编号，是则将前面作为一条提交到cy；
        // 2.如单据号跟前面相同，则合并子表记录
        String lastCGNum = null;
        for (int i=0; i<JdyCGDD.length; i++) {
            String[] curCGDD = JdyCGDD[i];
            // 单据编号默认放第一个
            String curNum = curCGDD[0];
            // 判断是否已在氚云存在
            if (cache.getIfPresent(curNum) != null) {
                continue;
            }
            // 调用氚云接口查询，有则写入缓存，并continue
            if (!(lastCGNum != null && (lastCGNum.equals(curNum))) && checkHasCyNum(curNum)) {
                cache.put(curNum, "存在");
                continue;
            }
            // 尚不存在，同步到氚云
            if (lastCGNum != null && !(lastCGNum.equals(curNum))) {
                // 提交氚云数据
                createCYData(schemaCodeCYFLCG2, generateCyFlcgdJson(cyCgddVo));
                // 提交后，将cyCgddVo置null，从新开始新数据组装
                cyCgddVo = null;
            }
            // 拼接氚云主从表数据
            if (cyCgddVo == null) {
                cyCgddVo = new CyCGDDVO();
                List<CyCGXQXX> cgxqList = new ArrayList<CyCGXQXX>();
                cyCgddVo.setCgxqList(cgxqList);

                cyCgddVo.setXdrq(curCGDD[1]);
                cyCgddVo.setGys(curCGDD[3]);
                cyCgddVo.setDjbh(curCGDD[0]);

                cyCgddVo.setYwywb(curCGDD[19]);
                cyCgddVo.setCjrwb(curCGDD[11]);
            }
            cyCgddVo.getCgxqList().add(generateCyCGXQXXFromCy(curCGDD));
            lastCGNum = curNum;

        }
        if (cyCgddVo != null) {
            // 提交氚云数据
            createCYData(schemaCodeCYFLCG2, generateCyFlcgdJson(cyCgddVo));
        }
    }

    public boolean checkHasCyNum(String curNum) {
        String strFilter = "{\"FromRowNum\":   0,\"RequireCount\": false,\"ReturnItems\": [],   " +
                "\"SortByCollection\": [],\"ToRowNum\": 500,   \"Matcher\":{\"Type\":\"And\",   \"Matchers\":[{\"Type\":\"And\"," +
                "\"Matchers\":[{\"Type\":\"Item\",\"Name\":\"F0000045\",\"Operator\":2,\"Value\":\"" + curNum + "\"}]}]}}";
//                        String strFilter = "{\"FromRowNum\":0,\"RequireCount\":false,\"ReturnItems\":["ObjectId", "F0000039", "F0000013"],\"SortByCollection\":[],\"ToRowNum\":500,\"Matcher\":{\"Type\":\"And\",\"Matchers\":[{\"Type\":\"Item\",\"Name\":\"F0000039\",\"Operator\":2,\"Value\":\"CGDD007035-119130\"}]}}";
        String reData = queryCYDatas(schemaCodeCYFLCG2, strFilter);
        if (reData.contains("{\"Successful\":true,")) {
            if (reData.length() > 110) {
                log.info("**" + curNum + "**  查询氚云，结论：已存在。返回信息为：" + reData);
                return true;
            } else {
                log.info("**" + curNum + "**  查询氚云，结论：不存在。返回信息为：" + reData);
                return false;
            }
        } else {
            log.info("**" + curNum + "**  查询氚云，结论：不存在。返回信息为：" + reData);
            return false;
        }
    }
    public boolean checkHasCyNum(String schemaCode, String checkFieldName, String curNum) {
        String strFilter = "{\"FromRowNum\":   0,\"RequireCount\": false,\"ReturnItems\": [],   " +
                "\"SortByCollection\": [],\"ToRowNum\": 500,   \"Matcher\":{\"Type\":\"And\",   \"Matchers\":[{\"Type\":\"And\"," +
                "\"Matchers\":[{\"Type\":\"Item\",\"Name\":\"" + checkFieldName + "\",\"Operator\":2,\"Value\":\"" + curNum + "\"}]}]}}";
//                        String strFilter = "{\"FromRowNum\":0,\"RequireCount\":false,\"ReturnItems\":["ObjectId", "F0000039", "F0000013"],\"SortByCollection\":[],\"ToRowNum\":500,\"Matcher\":{\"Type\":\"And\",\"Matchers\":[{\"Type\":\"Item\",\"Name\":\"F0000039\",\"Operator\":2,\"Value\":\"CGDD007035-119130\"}]}}";
        String reData = queryCYDatas(schemaCode, strFilter);
        if (reData.contains("{\"Successful\":true,")) {
            if (reData.length() > 110) {
                log.info("**" + curNum + "**  查询氚云，结论：已存在。返回信息为：" + reData);
                return true;
            } else {
                log.info("**" + curNum + "**  查询氚云，结论：不存在。返回信息为：" + reData);
                return false;
            }
        } else {
            log.info("**" + curNum + "**  查询氚云，结论：不存在。返回信息为：" + reData);
            return false;
        }
    }

    /**
     * 氚云辅料采购订单字表信息创建
     * @param curCGDD
     * @return
     */
    public CyCGXQXX generateCyCGXQXXFromCy(String[] curCGDD) {
        CyCGXQXX cyCgxqxx = new CyCGXQXX();
        cyCgxqxx.setDdh(curCGDD[16]);
        cyCgxqxx.setKhhth(curCGDD[5]);
        cyCgxqxx.setDycp(curCGDD[18]);
        cyCgxqxx.setWlmc(curCGDD[6]);
        cyCgxqxx.setFlgg(curCGDD[17]);

        cyCgxqxx.setCgsl(curCGDD[7]);
        cyCgxqxx.setFljhsj(curCGDD[9]);
        cyCgxqxx.setBz(curCGDD[22]);
        cyCgxqxx.setBcbzsm(curCGDD[10]);
        cyCgxqxx.setZxzzyq(curCGDD[20]);

        cyCgxqxx.setSysm(curCGDD[21]);

        return cyCgxqxx;
    }

    public CySCJHDDBCP generateCyScjhddBcp(ArrayList<String> curScjhdd) {
        CySCJHDDBCP cyScjjddBcp = new CySCJHDDBCP();
        cyScjjddBcp.setDdhZb(curScjhdd.get(31));
        cyScjjddBcp.setBcpmc(curScjhdd.get(13));
        cyScjjddBcp.setCpysxg(curScjhdd.get(14));
        cyScjjddBcp.setCl(curScjhdd.get(15));
        cyScjjddBcp.setKz(curScjhdd.get(16));
        cyScjjddBcp.setDdsl(curScjhdd.get(17));
        cyScjjddBcp.setBz(curScjhdd.get(18));
        cyScjjddBcp.setMjbh(curScjhdd.get(19));
        cyScjjddBcp.setCms(curScjhdd.get(20));
        cyScjjddBcp.setDdylkg(curScjhdd.get(24));

        return cyScjjddBcp;
    }

    public String generateCyFlcgdJson(CyCGDDVO cyCgddVo) {
        Gson gson = new Gson();
        String cgddCyJson = gson.toJson(cyCgddVo);
        log.debug("氚云辅料采购单-json-中间过程字符串： " + cgddCyJson);
        cgddCyJson = cgddCyJson.replaceAll("\"xdrq\"", "\"F0000031\"").replaceAll("\"gys\"", "\"F0000029\"")
                .replaceAll("\"djbh\"", "\"F0000045\"").replaceAll("\"ywywb\"", "\"F0000046\"")
                .replaceAll("\"cjrwb\"", "\"F0000047\"").replaceAll("\"cgxqList\"", "\"D279357Fora1xciuumk2loiybxq6rxoe7\"")
                .replaceAll("\"ddh\"", "\"F0000033\"").replaceAll("\"khhth\"", "\"F0000034\"")
                .replaceAll("\"dycp\"", "\"F0000035\"").replaceAll("\"wlmc\"", "\"F0000036\"")
                .replaceAll("\"flgg\"", "\"F0000037\"").replaceAll("\"cgsl\"", "\"F0000038\"")
                .replaceAll("\"fljhsj\"", "\"F0000039\"").replaceAll("\"bz\"", "\"F0000040\"")
                .replaceAll("\"bcbzsm\"", "\"F0000041\"").replaceAll("\"zxzzyq\"", "\"F0000042\"")
                .replaceAll("\"sysm\"", "\"F0000043\"");
        return cgddCyJson;

        /**
         * {"xdrq":"2023-06-06T00:00:00","gys":"台州市森迪印刷有限公司","djbh":"CGDD007153","ywywb":"牟李霞","cjrwb":"牟李霞",
         * "cgxqList":[{"ddh":"230314","khhth":"SX230047","dycp":"南瓜笑脸杯-弯眉毛","wlmc":"标签","flgg":"5X5","cgsl":"16008.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"迷你吹塑小南瓜","wlmc":"标签","flgg":"16x14","cgsl":"18024.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"骷髅高脚杯","wlmc":"标签","flgg":"5X5","cgsl":"9612.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"大号三角桶","wlmc":"标签","flgg":"5X5","cgsl":"4800.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"南瓜笑脸高脚杯","wlmc":"标签","flgg":"5X5","cgsl":"14016.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"PS南瓜碗","wlmc":"标签","flgg":"5X5","cgsl":"8004.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"吹塑小水壶","wlmc":"标签","flgg":"5X5","cgsl":"14022.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"PP杯","wlmc":"标签","flgg":"2.5x16.1","cgsl":"18036.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"鬼脸杯","wlmc":"标签","flgg":"5X5","cgsl":"5016.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"爱心高脚杯","wlmc":"标签","flgg":"5X5","cgsl":"12000.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""},
         * {"ddh":"230314","khhth":"SX230047","dycp":"多边形蜘蛛碗","wlmc":"标签","flgg":"5X5","cgsl":"7200.0","fljhsj":"2023-06-10T00:00:00","bz":"","bcbzsm":"","zxzzyq":"","sysm":""}]}
         */
    }

    public String generateCyScjhddJson(CySCJHDDVO cyScjhddVo) {
        Gson gson = new Gson();
        String scjhddCyJson = gson.toJson(cyScjhddVo);
        log.debug("氚云生产计划订单-json-中间过程字符串： " + cyScjhddVo);
        scjhddCyJson = scjhddCyJson.replaceAll("\"jddjbh\"", "\"F0000068\"").replaceAll("\"ddh\"", "\"F0000049\"")
                .replaceAll("\"cpmc\"", "\"F0000002\"").replaceAll("\"hth\"", "\"F0000012\"")
                .replaceAll("\"jb\"", "\"F0000033\"").replaceAll("\"ecjg\"", "\"F0000036\"")
                .replaceAll("\"yhsj\"", "\"F0000051\"").replaceAll("\"chsj\"", "\"F0000050\"")
                .replaceAll("\"pohh\"", "\"F0000063\"").replaceAll("\"zxl\"", "\"F0000055\"")
                .replaceAll("\"gdxs\"", "\"F0000054\"").replaceAll("\"gdsl\"", "\"F0000056\"")
                .replaceAll("\"khscyq\"", "\"F0000040\"").replaceAll("\"scjhddbcpList\"", "\"F4d4d54528a2c4ed3abefa1a7a1370e81\"")
                .replaceAll("\"ddhZb\"", "\"F0000044\"").replaceAll("\"bcpmc\"", "\"F0000025\"")
                .replaceAll("\"cpysxg\"", "\"F0000026\"").replaceAll("\"cl\"", "\"F0000028\"")
                .replaceAll("\"kz\"", "\"F0000045\"").replaceAll("\"ddsl\"", "\"F0000046\"")
                .replaceAll("\"bz\"", "\"F0000031\"").replaceAll("\"mjbh\"", "\"F0000048\"")
                .replaceAll("\"cms\"", "\"F0000062\"").replaceAll("\"ywy\"", "\"F0000069\"")
                .replaceAll("\"ddylkg\"", "\"F0000047\"");
        return scjhddCyJson;
    }

    /*本接口用于实现采购订单 (PUR_PurchaseOrder)的单据查询功能*/
//    @Test
    public String[][] queryPurchaseOrderBySort(String beginDate, String endDate) {
//        FNumber = "CGDD007358";
//        String modifyDate = "2023-7-13";
//        String modifyDate = LocalDate.now().minusDays(5).toString();
        //0-5 单据编号, 采购日期, 采购员, 供应商, 采购订单号
        //5-5 客户合同号, 物料名称, 采购数量, 规格型号, 交货日期
        //10-4 补充说明备注, 创建人, 创建日期, 产品名称
        //14-6 实体主键, 单据状态, 朔翔号（订单号）, 备注1（辅料规格; 先占位）, 对应产品（产品名称）, 跟单员名称（业务员）
        //20 纸箱纸质要求（F_QWE_TEXT）, 使用说明（F_QWE_TEXT2）, 备注（FEntryNote）, 审核日期,
        // 最后： FModifyDate  ($$FAUXPROPID__FF100002,)
        // [[101527, 2023-07-06T00:00:00, 0, CGDD007360, null, 1TSGW8, null, 270048.0, 张 结算, 2023-07-10T00:00:00, 289139, 2023-07-05T17:54:50.953, 107592, B]]
        String fieldstr = "FBillNo,FDate,FPurchaserId.Fname,FSupplierId.Fname,FPURCHASEORDERNO, " +
                "FMtoNo,FMaterialName,FQty,FModel,FDeliveryDate," +
                "F_qwe_Text1, FCreatorId.fname,FCreateDate, F_qwe_Base, " +
                "FID,FDocumentStatus, F_qwe_Text4, FAUXPROPID.FF100002, F_QWE_BASE1.fname, F_qwe_Text6," +
                "F_QWE_TEXT, F_QWE_TEXT2, FEntryNote, FApproveDate,  " +
                "FModifyDate";
        String json = "{\n" +
                "    \"FormId\": \"PUR_PurchaseOrder\",\n" +
                "    \"FieldKeys\": \"" + fieldstr + "\",\n" +
                "    \"FilterString\": \"FApproveDate>=\'" + beginDate + "\' and FApproveDate<=\'" + endDate + "\' and FDocumentStatus=\'C\'\",\n" +
                "    \"OrderString\": \" FBillNo \",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 2000,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        String result = null;
        try {
            result = String.valueOf(api.executeBillQuery(json));
        } catch (Exception e) {
            log.error(beginDate + " -- " + endDate + "区间，取金蝶已审核通过的单据失败。返回信息：" , e);
        }
        if (result != null && result.length() > 2) {
            String[][] formatResult = formatJdyData(result);
            log.debug(beginDate + " -- " + endDate + "区间，取金蝶已审核通过的单据成功。返回信息：" + result);
            return formatResult;
        } else {
            return null;
        }
    }

    /**
     * 生产计划订单   金蝶到氚云
     * @param beginDate
     * @param endDate
     * @throws Exception
     */
    public void processSCJHDDJdy2Cy(String beginDate, String endDate) throws Exception {
        // 查询Jdy数据，入参：头一天日期；出参：二维数组，空返回null
        ArrayList<ArrayList<String>> list = queryJdyScjhddBySort(beginDate, endDate);
        if (list == null || list.size()==0) {
            return;
        }
        // 氚云生产计划订单vo
        CySCJHDDVO cyScjhddVo = null;
        // 对Jdy循环处理。
        // 0.判断该单据在cy是否存在，存在则对所有该单据continue（利用java自带缓存）
        // 1.按顺序判断是否新单据编号，是则将前面作为一条提交到cy；
        // 2.如单据号跟前面相同，则合并子表记录
        String lastCGNum = null;
        String firstZb1Num = null;
        HashSet<String> setZxl = null;
        for (int i=0; i<list.size(); i++) {
            ArrayList<String> curScjhdd = list.get(i);
            // 单据编号默认放第一个
            String curNum = curScjhdd.get(0);
            // 判断是否已在氚云存在
            if (cache.getIfPresent(curNum) != null) {
                continue;
            }
            // 调用氚云接口查询，有则写入缓存，并continue
            if (!(lastCGNum != null && (lastCGNum.equals(curNum))) && checkHasCyNum(schemaCodeSCJHDD, "F0000068", curNum)) {
                cache.put(curNum, "存在");
                continue;
            }
            // 尚不存在，同步到氚云
            if (lastCGNum != null && !(lastCGNum.equals(curNum))) {
                String zxlHb = hbZxl(setZxl);
                cyScjhddVo.setZxl(zxlHb);
                // 提交氚云数据
                createCYData(schemaCodeSCJHDD, generateCyScjhddJson(cyScjhddVo), "true");
                // 提交后，将cyScjhddVo置null，从新开始新数据组装
                cyScjhddVo = null;
            }
            // 拼接氚云主从表数据
            if (cyScjhddVo == null) {
                cyScjhddVo = new CySCJHDDVO();
                List<CySCJHDDBCP> bcpList = new ArrayList<CySCJHDDBCP>();
                cyScjhddVo.setScjhddbcpList(bcpList);

                cyScjhddVo.setJddjbh(curNum);
                cyScjhddVo.setDdh(curScjhdd.get(31));
                cyScjhddVo.setCpmc(curScjhdd.get(3));
                cyScjhddVo.setHth(curScjhdd.get(30));
                cyScjhddVo.setJb(curScjhdd.get(4));

                cyScjhddVo.setEcjg(curScjhdd.get(5));
                cyScjhddVo.setYhsj(curScjhdd.get(6));
                cyScjhddVo.setChsj(curScjhdd.get(7));
                cyScjhddVo.setPohh(curScjhdd.get(8));
//                cyScjhddVo.setZxl(curScjhdd.get(9));
                cyScjhddVo.setYwy(curScjhdd.get(9));

                cyScjhddVo.setGdxs(curScjhdd.get(10));
                cyScjhddVo.setGdsl(curScjhdd.get(11));
                cyScjhddVo.setKhscyq(curScjhdd.get(12));


                // 记录第1个子表的第一条记录id
                firstZb1Num = curScjhdd.get(21);
                setZxl = new HashSet<>();
            }
            if (firstZb1Num != null && firstZb1Num.equals(curScjhdd.get(21))) {
                cyScjhddVo.getScjhddbcpList().add(generateCyScjhddBcp(curScjhdd));
            }
            setZxl.add(curScjhdd.get(23).trim());
            lastCGNum = curNum;
        }
        if (cyScjhddVo != null) {
            String zxlHb = hbZxl(setZxl);
            cyScjhddVo.setZxl(zxlHb);
            // 提交氚云数据
            createCYData(schemaCodeSCJHDD, generateCyScjhddJson(cyScjhddVo), "true");
        }
    }

    /**
     * 合并装箱率字段
     * @param beginDate
     * @param endDate
     * @return
     */
    public String hbZxl(HashSet<String> setZxl) {
        StringBuilder builder = new StringBuilder();
        for (String element : setZxl) {
            builder.append(element).append(", ");
        }

        // 删除最后一个逗号和空格
        if (builder.length() > 0) {
            builder.delete(builder.length() - 2, builder.length());
        }
        return builder.toString();
    }

    @Test
    public ArrayList<ArrayList<String>> queryJdyScjhddBySort(String beginDate, String endDate) {
//        String FNumber = "20211101-0005";  //20230801-0008     20230801-0009   20230802-0020    20230807-0001
//        String FNumber = "20230801-0004";
//        String FNumber = "20230801-0008";
        //0-5 单据编号,审核日期, 单据状态, 产品名称（子）, 级别,
        //5-5 二次加工, 验货日, 交货日期, 货号, 销售员代码,
        //10-5 总箱数, 产品数量合计, 备注, 配件名称, 颜色,
        //15-5 材质, 重量g, 需求数量（个), 备注（子表）, 模具编号,
        //20-5 出模率, 子表1ID, 子表2ID, 装箱率（子表1）, 订单用料
        //25-5 预留字段5个，1--5
        //   合并客户合同号, 朔翔号
        String fieldstr = "FBillNo, F_QWE_DATE19, FBillStatus1,  F_qwe_Base3.Fname, F_qwe_Text7, " +
                " F_qwe_Text2, F_qwe_Date1, F_qwe_Date, F_qwe_Text19, F_qwe_Text8, " +
                " F_qwe_Decimal5, F_qwe_Decimal1, F_qwe_Text21, F_qwe_Base.Fname, F_qwe_Text16, " +
                " F_qwe_Text17, F_qwe_BaseProperty1, F_qwe_Decimal, F_qwe_Text3, F_qwe_BaseProperty3, " +
                " F_qwe_BaseProperty4, F_qwe_Entity1_FEntryID, F_qwe_Entity_FEntryID, F_qwe_Base4.fname, F_ddyl, " +
                " 'yuliu1', 'yuliu2','yuliu3','yuliu4','yuliu5'," +
                " 'ly-split', F_qwe_Text5, 'ly-split', F_qwe_Text6";
        String json = "{\n" +
                "    \"FormId\": \"k1583e5bde51d45a299c0126e98951888\",\n" +
                "    \"FieldKeys\": \"" + fieldstr + "\",\n" +
                "    \"FilterString\": \"F_QWE_DATE19>=\'" + beginDate + "\' and F_QWE_DATE19<=\'" + endDate + "\' and FBillStatus1=\'1\'\",\n" +
//                "    \"FilterString\": \"FBillNo=\'" + FNumber + "\'\",\n" +
                "    \"OrderString\": \" FBillNo, F_qwe_Entity1_FEntryID, F_qwe_Entity_FEntryID   \",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 0,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        String result = null;
        try {
            result = String.valueOf(api.executeBillQuery(json));
        } catch (Exception e) {
            log.error(beginDate + " -- " + endDate + "区间，取金蝶已审核通过的单据失败。返回信息：" , e);
        }
        if (result != null && result.length() > 2) {
            ArrayList<ArrayList<String>> list = formatJdyScjhddData(result);
            log.debug(beginDate + " -- " + endDate + "区间，取金蝶已审核通过的单据成功。返回信息：" + list);
            return list;
        } else {
            return null;
        }
    }

    /**
     * 金蝶云生产计划订单数据格式化
     * @param str
     * @return
     */
    public ArrayList<ArrayList<String>> formatJdyScjhddData(String str) {
        ArrayList<ArrayList<String>> resultList = new ArrayList<>();
        // 去掉字符串中的空格
        str = str.replaceAll("\\s+","");

        // 去掉每个元素的方括号，并将逗号分隔的元素转换为数组
        String[] arr = str.substring(2, str.length() - 2).split("\\],\\[");

        // 将每个一维数组元素转换为Java数组
        String[][] result = new String[arr.length][];
        for (int i = 0; i < arr.length; i++) {
            String jdyScjhddRow = arr[i];
            int firstSplist = jdyScjhddRow.indexOf(",ly-split,");
            String jdy1 = jdyScjhddRow.substring(0, firstSplist);
            ArrayList<String> rowList = new ArrayList<String>(Arrays.asList(jdy1.split(",")));
            String jdy2 = jdyScjhddRow.substring(firstSplist + 10);
            ArrayList<String> rowListTmp = new ArrayList<String>(Arrays.asList(jdy2.split(",ly-split,")));
            rowList.addAll(rowListTmp);
            resultList.add(rowList);
        }

        return resultList;
    }
}
